package com.em.tuppence.crypto;

import java.security.InvalidParameterException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;

import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class CryptoProvider {

	public static byte[] generateSecret() {
		
		byte[] result = null;
		
		Security.addProvider(new BouncyCastleProvider());
		try {
			SecureRandom rng = SecureRandom.getInstance("SHA1PRNG");

			int seedBytes = 512;
			byte[] seed = rng.generateSeed(seedBytes);
			rng.setSeed(seed);
			
			result = new byte[seedBytes];
			rng.nextBytes(result);			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}			
		
		return result;
	}
	
	private static String generateId(byte[] salt, byte[] message) {
		String id = null;
		
		Security.addProvider(new BouncyCastleProvider());
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-512","BC");
			if(salt != null) {
				digest.update(salt);
			}			
			byte[] messageDigestByteArray = digest.digest(message);
			id = Hex.encodeHexString(messageDigestByteArray);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		}		
		
		//last 10
		if(id.length() > 10) {
			id = id.substring(id.length() - 10);
		}
		
		return id;
	}
	
	public static String generateId(String fromUrl) {
		if(fromUrl == null) {
			throw new InvalidParameterException("User OpenID URL must not be null.");
		}
		return CryptoProvider.generateId(null, fromUrl);
	}

	public static String generateId(String salt, String fromUrl) {
		byte[] saltBytes = (salt == null) ? null : salt.toUpperCase().getBytes();
		byte[] messageBytes = fromUrl.toUpperCase().getBytes();
		return CryptoProvider.generateId(saltBytes, messageBytes);
	}

	
}
